package com.yqy.controller;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.UUID;

@Controller
public class FileUpAndDownTestController {
    @RequestMapping("/test/download")
    public ResponseEntity<byte[]> download(HttpSession session) throws IOException {
        //获取ServletContext对象
        ServletContext context = session.getServletContext();
        //获取服务器中文件的真实路径
        String realPath = context.getRealPath("img");
        realPath = realPath + File.separator + "1.jpg";
        //创建输入流
        InputStream inputStream=new FileInputStream(realPath);
        //创建字节数组并通过inputStream.available()获取文件的字节数
        byte[] data=new byte[inputStream.available()];
        //将流读入字节数组
        inputStream.read(data);
        //创建HttpHeaders对象设置响应头信息
        MultiValueMap<String, String> headers = new HttpHeaders();
        //设置下载方式和下载文件名
        headers.add("Content-Disposition", "attachment;filename=1.jpg");
        //设置响应状态码
        HttpStatus status=HttpStatus.OK;
        //创建ResponseEntity对象
        ResponseEntity responseEntity=new ResponseEntity<>(data,headers,status);
        inputStream.close();
        return responseEntity;
    }

    @RequestMapping("/test/upload")
    public String upload(MultipartFile photo,HttpSession session) throws IOException {
        //获取文件名
        String fileName = photo.getOriginalFilename();
        //获取文件后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //获取UUID
        String uuid=UUID.randomUUID().toString();
        //拼接成新的文件名
        fileName=uuid+suffixName;
        //获取ServletContext对象
        ServletContext context = session.getServletContext();
        //获取photo目录真实路径
        String realPath = context.getRealPath("photo");
        //创建realPath的File对象
        File file=new File(realPath);
        //判断photo文件夹是否存在
        if (!file.exists()){
            file.mkdir();
        }
        //获取最终路径
        String finalPath=realPath+File.separator+fileName;
        //上传文件
        photo.transferTo(new File(finalPath));
        return "success";
    }
}
